// DOM 元素获取
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const progressThumb = document.getElementById('progress-thumb');
const bargainButton = document.getElementById('bargain-button');
const bargainResult = document.getElementById('bargain-result');
const currentPrice = document.getElementById('current-price');
const participantCount = document.getElementById('participant-count');
const activityList = document.getElementById('activity-list');
const successModal = document.getElementById('success-modal');
const modalClose = document.getElementById('modal-close');
const countdown = document.getElementById('countdown');

// 游戏状态
let remainingPrice = 100.00;
const totalPrice = 100.00;
let clickCount = 0;
let participants = 1234;
let isGameComplete = false;

// 倒计时功能
function startCountdown() {
    let hours = 23;
    let minutes = 59;
    let seconds = 59;
    
    setInterval(() => {
        seconds--;
        if (seconds < 0) {
            seconds = 59;
            minutes--;
            if (minutes < 0) {
                minutes = 59;
                hours--;
                if (hours < 0) {
                    hours = 23;
                }
            }
        }
        
        const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        countdown.textContent = timeString;
    }, 1000);
}

// 生成随机用户名
function generateRandomUser() {
    const surnames = ['张', '李', '王', '刘', '陈', '杨', '赵', '黄', '周', '吴'];
    const randomSurname = surnames[Math.floor(Math.random() * surnames.length)];
    return randomSurname + '**';
}

// 添加砍价记录
function addBargainRecord(amount) {
    const newRecord = document.createElement('div');
    newRecord.className = 'activity-item';
    newRecord.innerHTML = `
        <span class="user">${generateRandomUser()}</span> 刚刚砍了 <span class="amount">￥${amount.toFixed(2)}</span>
    `;
    
    // 添加进入动画
    newRecord.style.opacity = '0';
    newRecord.style.transform = 'translateY(-10px)';
    
    activityList.insertBefore(newRecord, activityList.firstChild);
    
    // 触发动画
    setTimeout(() => {
        newRecord.style.transition = 'all 0.3s ease';
        newRecord.style.opacity = '1';
        newRecord.style.transform = 'translateY(0)';
    }, 100);
    
    // 保持最多3条记录
    if (activityList.children.length > 3) {
        activityList.removeChild(activityList.lastChild);
    }
}

// 更新进度条
function updateProgress() {
    const progress = (totalPrice - remainingPrice) / totalPrice * 100;
    progressBar.style.width = `${progress}%`;
    
    // 更新进度条拇指位置
    progressThumb.style.right = `${-6 - (progress * 0.1)}px`;
    
    // 更新价格显示
    const currentPriceValue = 199 - (totalPrice - remainingPrice);
    currentPrice.textContent = `￥${currentPriceValue.toFixed(2)}`;
    
    // 更新进度文本
    const remainingElement = progressText.querySelector('.remaining-amount');
    remainingElement.textContent = `还差 ￥${remainingPrice.toFixed(2)}`;
    
    // 更新参与人数
    participants += Math.floor(Math.random() * 3) + 1;
    participantCount.innerHTML = `已有 <strong>${participants.toLocaleString()}</strong> 人参与`;
}

// 创建粒子效果
function createParticles(x, y) {
    const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57'];
    
    for (let i = 0; i < 8; i++) {
        const particle = document.createElement('div');
        particle.style.position = 'fixed';
        particle.style.left = x + 'px';
        particle.style.top = y + 'px';
        particle.style.width = '6px';
        particle.style.height = '6px';
        particle.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        particle.style.borderRadius = '50%';
        particle.style.pointerEvents = 'none';
        particle.style.zIndex = '9999';
        
        document.body.appendChild(particle);
        
        const angle = (Math.PI * 2 * i) / 8;
        const velocity = 100 + Math.random() * 50;
        const vx = Math.cos(angle) * velocity;
        const vy = Math.sin(angle) * velocity;
        
        let posX = x;
        let posY = y;
        let opacity = 1;
        
        const animate = () => {
            posX += vx * 0.02;
            posY += vy * 0.02;
            opacity -= 0.02;
            
            particle.style.left = posX + 'px';
            particle.style.top = posY + 'px';
            particle.style.opacity = opacity;
            
            if (opacity > 0) {
                requestAnimationFrame(animate);
            } else {
                document.body.removeChild(particle);
            }
        };
        
        requestAnimationFrame(animate);
    }
}

// 按钮点击效果
function buttonClickEffect() {
    bargainButton.style.transform = 'scale(0.95)';
    setTimeout(() => {
        bargainButton.style.transform = 'scale(1)';
    }, 150);
}

// 显示成功弹窗
function showSuccessModal() {
    successModal.style.display = 'flex';
    
    // 添加庆祝效果
    setTimeout(() => {
        createParticles(window.innerWidth / 2, window.innerHeight / 2);
    }, 500);
}

// 主要砍价逻辑
bargainButton.addEventListener('click', (e) => {
    if (isGameComplete) return;
    
    clickCount++;
    buttonClickEffect();
    
    // 创建点击粒子效果
    const rect = bargainButton.getBoundingClientRect();
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;
    createParticles(centerX, centerY);
    
    let bargainAmount;
    
    // 秘密成功条件：点击10次
    if (clickCount === 10) {
        bargainAmount = remainingPrice;
        bargainResult.innerHTML = `🎉 <strong>恭喜！你砍了 ￥${bargainAmount.toFixed(2)}！</strong>`;
        bargainResult.style.color = '#27ae60';
    } else {
        // 正常砍价逻辑 - 永远砍不完
        bargainAmount = Math.random() * 8 + 0.01;
        
        // 确保永远不会完全砍完（除非是第10次点击）
        if (remainingPrice - bargainAmount <= 0.01) {
            bargainAmount = remainingPrice - 0.01;
        }
        
        // 显示砍价结果
        const messages = [
            `太棒了！你砍了 ￥${bargainAmount.toFixed(2)}！`,
            `哇！砍掉了 ￥${bargainAmount.toFixed(2)}！`,
            `厉害！成功砍价 ￥${bargainAmount.toFixed(2)}！`,
            `不错！砍了 ￥${bargainAmount.toFixed(2)}！`
        ];
        
        bargainResult.innerHTML = `⚡ ${messages[Math.floor(Math.random() * messages.length)]}`;
        bargainResult.style.color = '#4ecdc4';
    }
    
    // 更新剩余价格
    remainingPrice -= bargainAmount;
    if (remainingPrice < 0) remainingPrice = 0;
    
    // 更新界面
    updateProgress();
    addBargainRecord(bargainAmount);
    
    // 检查是否成功
    if (remainingPrice === 0) {
        isGameComplete = true;
        bargainButton.disabled = true;
        bargainButton.innerHTML = `
            <span class="button-icon">🎉</span>
            <span class="button-text">砍价成功！</span>
        `;
        bargainButton.style.background = 'linear-gradient(45deg, #27ae60, #2ecc71)';
        
        setTimeout(() => {
            showSuccessModal();
        }, 1000);
    }
    
    // 添加按钮文字变化效果
    if (!isGameComplete) {
        const buttonTexts = [
            '再砍一刀！',
            '继续砍价！',
            '加油砍价！',
            '帮好友砍一刀',
            '砍砍砍！'
        ];
        
        if (clickCount > 1) {
            const buttonText = bargainButton.querySelector('.button-text');
            buttonText.textContent = buttonTexts[Math.floor(Math.random() * buttonTexts.length)];
        }
    }
});

// 分享按钮事件
document.getElementById('share-wechat').addEventListener('click', () => {
    bargainResult.innerHTML = '📱 正在打开微信分享...';
    bargainResult.style.color = '#1aad19';
    setTimeout(() => {
        bargainResult.innerHTML = '分享成功！快让好友来帮你砍价吧！';
    }, 1500);
});

document.getElementById('share-moments').addEventListener('click', () => {
    bargainResult.innerHTML = '🔄 正在分享到朋友圈...';
    bargainResult.style.color = '#4267B2';
    setTimeout(() => {
        bargainResult.innerHTML = '已分享到朋友圈！等待好友砍价中...';
    }, 1500);
});

document.getElementById('share-qq').addEventListener('click', () => {
    bargainResult.innerHTML = '🐧 正在分享到QQ空间...';
    bargainResult.style.color = '#12b7f5';
    setTimeout(() => {
        bargainResult.innerHTML = 'QQ空间分享成功！';
    }, 1500);
});

// 关闭成功弹窗
modalClose.addEventListener('click', () => {
    successModal.style.display = 'none';
});

// 点击弹窗外部关闭
successModal.addEventListener('click', (e) => {
    if (e.target === successModal) {
        successModal.style.display = 'none';
    }
});

// 模拟其他用户砍价活动
function simulateOtherUsers() {
    setInterval(() => {
        if (!isGameComplete && Math.random() < 0.3) {
            const amount = Math.random() * 5 + 0.5;
            addBargainRecord(amount);
            
            // 更新参与人数
            participants += Math.floor(Math.random() * 2) + 1;
            participantCount.innerHTML = `已有 <strong>${participants.toLocaleString()}</strong> 人参与`;
        }
    }, 3000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    startCountdown();
    simulateOtherUsers();
    updateProgress();
    
    // 添加一些初始的砍价记录
    setTimeout(() => addBargainRecord(2.33), 500);
    setTimeout(() => addBargainRecord(1.88), 1000);
    setTimeout(() => addBargainRecord(3.66), 1500);
});

// 添加键盘快捷键（隐藏功能）
document.addEventListener('keydown', (e) => {
    // 按下 Ctrl + Shift + S 立即成功
    if (e.ctrlKey && e.shiftKey && e.key === 'S') {
        if (!isGameComplete) {
            clickCount = 9; // 下次点击就会成功
            bargainResult.innerHTML = '🎯 秘密模式已激活！再点击一次按钮即可成功！';
            bargainResult.style.color = '#e74c3c';
        }
    }
});